package com.pi.pro.xcmg.am.was.web.cust.controller;

import com.alibaba.fastjson.JSONArray;
import com.pi.common.CodesConstants;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.framework.core.util.csv.CsvExporter;
import com.pi.framework.web.util.CsvView;
import com.pi.pro.xcmg.am.was.edi.infor.common.InforWasExchangeSupport;
import com.pi.pro.xcmg.am.was.edi.infor.dto.reply.FuncReplyData;
import com.pi.pro.xcmg.am.was.edi.infor.dto.reply.TaskReportResultDto;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.entity.TwtActTransList;
import com.pi.wms.entity.VwtActChangeTransList;
import com.pi.wms.service.ChangeTransService;
import com.pi.wms.service.TransService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Controller
@RequestMapping("/inventory/invtrans/ca")
public class CustApplyInventoryTransController extends BaseCrudController<VwtActChangeTransList, Long> {

	@Autowired
	private ChangeTransService service;

	@Autowired
	private WasCustomWorkService wasCustomWorkService;
	
	@Override
	protected ICrudService<VwtActChangeTransList, Long> getCrudService() {
	    return service;
	}

	@Override
	protected String getPrefix() {
		return "invtrans";
	}

	//
	@PostMapping("repost")
	public String repost(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
						  RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String m="";
		String mr="";
        TwtActTransList tran=null;
		if ((ids == null) || (ids.length==0)) {
			addSuccessMessage(redirectAttributes, "重传成功");
			return this.redirect("");
		}
		List<FuncReplyData<TaskReportResultDto>> resultDatas=this.wasCustomWorkService.handleWasTransDataToXwms(Arrays.asList(ids), true, SecurityUtils.getLoginUsername());
		for (FuncReplyData<TaskReportResultDto> d : resultDatas) {
		    if (d==null){
                continue;
            }
            mr= InforWasExchangeSupport.errorMessage(d);
		    if (!StringUtils.isNullOrBlank(mr)){
                m=m+mr+"\nr";
            }
		}
		if(!StringUtils.isNullOrBlank(m)){
			addErrorMessage(redirectAttributes, "重传失败"+m);
			return this.redirect("");
		}
		addSuccessMessage(redirectAttributes, "重传成功");
		return this.redirect("");
	}

	/**
	 * Description: 导出
	 */
	@PostMapping(value = { "/export" })
	public ModelAndView export(@RequestParam Map<String, Object> query, DataTablesInput input) {
		String inputParams = "";
		if (query.get("input")!=null){
			inputParams=query.get("input").toString();
		}
		if (StringUtils.isNotEmpty(inputParams)) {
			input = JSONArray.parseObject(inputParams, DataTablesInput.class);
		}
		input.setLength(-1);
//		DataTablesOutput<InventoryTrans> data = service.findAll(input, query);

//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("data", data != null ? data.getData() : null);
		String ymd = DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HHMMSS);
		final DataTablesInput ins = input;
		final Map<String, String> typeCodeNames=new HashMap<>();
		typeCodeNames.put(WmsConstants.TRANS_TYPE_RECEIVE,"入库");
		typeCodeNames.put(WmsConstants.TRANS_TYPE_SHIP,"出库");
		typeCodeNames.put(WmsConstants.TRANS_TYPE_ADJUST,"调整");
		typeCodeNames.put("MERGE","移动");

		CsvExporter<VwtActChangeTransList> exporter = new CsvExporter<VwtActChangeTransList>() {
			@Override
			public String[] header() {
				return "交易号,类型,物料,物料名称,单号,行号,数量,供应商,WBS,原托盘,目标托盘,起始库位,目标库位,交易时间,创建人,备注"
						.split(",");
			}

			@Override
			public Collection<VwtActChangeTransList> nextList(int pageSize, int page) {
				ins.setLength(pageSize);
				ins.setStart(page * pageSize);
				DataTablesOutput<VwtActChangeTransList> out = service.findAll(ins, query);
				return out == null ? null : out.getData();
			}

			@Override
			public Collection<String> toText(VwtActChangeTransList d) {
				List<String> item = new ArrayList<String>();
				item.add(d.getNumber() != null ? d.getNumber() : "");
				String typename=typeCodeNames.get(d.getType());
				if (com.pi.common.utils.StringUtils.isNullOrBlank(typename)){
					typename = d.getType();
				}
				item.add(typename);
				item.add(d.getMaterialCode() != null ? d.getMaterialCode() : "");
				item.add(d.getMaterialName() != null ? d.getMaterialName() : "");
				item.add(d.getDocNumber() != null ? d.getDocNumber() : "");
				item.add(d.getDocLinenumber() != null ? d.getDocLinenumber() : "");
				item.add(d.getQtyTransEach() != null ? String.valueOf(d.getQtyTransEach()) : "");
				item.add(d.getFromLotattr06() != null ? d.getFromLotattr06() : "");
				if ((StringUtils.isNullOrBlank(d.getFromLotattr07()))
                        ||(CodesConstants.COMMON_WILDCARD.equalsIgnoreCase(d.getFromLotattr07()))){
                    item.add("");
                }else {
                    item.add(d.getFromLotattr07().trim());
                }
				item.add(d.getFromContainNumber() != null ? d.getFromContainNumber() : "");
				item.add(d.getToContainNumber() != null ? d.getToContainNumber() : "");
				item.add(d.getFromLocCode() != null ? d.getFromLocCode() : "");
				item.add(d.getToLocCode() != null ? d.getToLocCode() : "");
				item.add(DateUtils.format(d.getOpenTime(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
				item.add(d.getCreatedBy() != null ? d.getCreatedBy() : "");
				item.add(d.getNotes() != null ? d.getNotes() : "");
				return item;
			}

		};
		return new ModelAndView(new CsvView(exporter, "inventory_trans_" + ymd));
	}

	//
	protected String redirect(String relativeUrl) {
		if(!StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
			relativeUrl = "/" + relativeUrl;
		}
		return "redirect:" + this.referUrl() + relativeUrl;
	}

	private String referUrl(){
		return "/inventory/invtrans/";
	}

}
